package com.quickcode.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by 张波 on 2019/10/24.
 */
@Slf4j
public class CyclicBarrierExample3 {

    public static CyclicBarrier cyclicBarrier = new CyclicBarrier(2,() -> {
        //当达到执行条件时，优先执行该线程
        log.info("cyclicBarrier is read!");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            log.error("cyclicBarrier exception:{}",e);
        }
        log.info("cyclicBarrier is runing!");

    });

    public final static int threadTotal = 20;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadTotal; ++i) {
            final int threadNumber = i;
            Thread.sleep(2000);
            executorService.execute(() -> {
                out(threadNumber);
            });
        }
        executorService.shutdown();
    }

    public static void out(int threadNum) {
        log.info("{} is read.", threadNum);
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            log.error("InterruptedException:{}", e);
        } catch (BrokenBarrierException e) {
            log.error("BrokenBarrierException:{}", e);
        }
        log.info("{} end.", threadNum);
    }
}
